// index.js
// 获取应用实例
const app = getApp()
const timelineData = require("../../server/timeline")
Page({
  data: {
    timeline: [],
    page: 1
  },
  onLoad() {
    this.retrieve()
  },
  onPullDownRefresh() {
    this.data.page = 1
    this.data.timeline.length = 0
    this.retrieve().finally(_ => wx.stopPullDownRefresh())
  },
  scrollToLower() {
    console.log(this.data.page++)
    this.data.page++
    this.retrieve()
  },
  retrieve() {
    let timeline = this.formatTimeline(timelineData.data)
    this.setData({
      timeline: [...this.data.timeline, ...timeline]
    })
    /* let url = `../../server/timeline.json?page=${this.data.page}`
    let result = await new Promise(function(resolve, reject) {
      wx.request({
        url,
        success(res) {
          resolve(res)
        },
        error(err) {
          reject(err)
        }
      })
    })
    result.then(res => {
      console.log(res)
      let timeline = this.formatTimeline(result.data)
      this.setData({
        timeline: [...this.data.timeline, ...timeline]
      })
    }).catch(err => {
      console.log(err)
    }) */
  },
  formatTimeline(items) {
    let now = new Date().getTime()
    var i = 0
    items.forEach(item => {
      item.avatar = `/static/image/${item.avatar % 4}.jpeg` //  旨在随机去图片
      item.created_at = now - (i++) * 6 * 60 * 60 * 1000
      item.time = app.globalData.api.humanFormatTime(item.created_at) //  旨在换算时间
    })
    return items
  },
  previewImage(event) {
    wx.previewImage({
      urls: [event.target.dataset.originalPic]
    })
  }
})
